package wcpackage.webapplication.view.loginpage;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import wcpackage.domain.entities.User;
import wcpackage.service.UserService;
import wcpackage.webapplication.UserSession;
import wcpackage.webapplication.view.BasePage;
import wcpackage.webapplication.view.welcomepage.WelcomePage;

/**
 * User: rabbit
 * Date: Jun 30, 2009
 * Time: 4:22:13 PM
 */
public class LoginPage extends BasePage {

    private User user;
    private Form form;

    @SpringBean
    private UserService userService;

    public LoginPage() {

        user = new User("", "");

        FeedbackPanel feeedback = new FeedbackPanel("feeedback");
        add(feeedback);

        form = new Form("siginForm");
        form.setModel(new CompoundPropertyModel(user));
        form.add(new TextField("login"));
        form.add(new PasswordTextField("password"));
        form.add(new Button("signInButton") {
            @Override
            public void onSubmit() {
                if (logedIn()) {
                    if (!continueToOriginalDestination()) {
                        setResponsePage(WelcomePage.class);
                    }
                } else {
                    error("Unknown login or password" + UserSession.get().getUser().getLogin() + " " + UserSession.get().getUser().getPassword());
                }
            }
        });
        add(form);
    }

    private boolean logedIn() {
        UserSession.get().setUser(userService.logIn(user.getLogin(), user.getPassword()));
        return UserSession.get().isAuthenticated();
    }
}
